package com.example.demo.controller;

import com.example.demo.commom.AjaxResult;
import com.example.demo.commom.JWTUtils;
import com.example.demo.entity.Commentinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.CommentinfoVO;
import com.example.demo.service.CommentService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-04-08
 * Time:21:54
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;

    @RequestMapping("/makecomment")
    public AjaxResult makeComment(Commentinfo commentinfo, HttpServletRequest request) {
        //1、判空
        if(commentinfo == null || commentinfo.getArtid() == null
        || !StringUtils.hasLength(commentinfo.getContent()) || commentinfo.getArtid() < 1) {
            return AjaxResult.fail("参数有误",-1);
        }
        //2、获取当前用户id，填入commentinfo中
        Userinfo userinfo = JWTUtils.getMemberIdByJwtToekn(request);
        if(userinfo == null || userinfo.getId() < 1) {
            return AjaxResult.fail("请登录后评论",-1);
        }
        commentinfo.setUserid(userinfo.getId());
        return AjaxResult.success(commentService.makeComment(commentinfo));
    }

    //展现已有的评论
    @RequestMapping("/querycomments")
    public AjaxResult queryComments(Commentinfo commentinfo) {

        //1、判空
        if(commentinfo == null || commentinfo.getArtid() == null || commentinfo.getArtid()<0) {
            return AjaxResult.fail("参数有误",-1);
        }

        //2、查询
        List<Commentinfo> list = commentService.queryComments(commentinfo);

        List<CommentinfoVO> lists = new ArrayList<>();
        //3、根据用户id获取用户名称
        //Spring提供的深克隆
        for(int i = 0;i<list.size();i++) {
            Commentinfo c1 = list.get(i);
            CommentinfoVO commentinfoVO = new CommentinfoVO();
            BeanUtils.copyProperties(c1,commentinfoVO);
            Integer uid = commentinfoVO.getUserid();
            if(uid == null || uid < 1) {
                return AjaxResult.fail("参数有误",-1);
            }
            Userinfo userinfo = userService.getUserById(uid);
            commentinfoVO.setUsername(userinfo.getUsername());
            lists.add(commentinfoVO);
        }
        //返回中----用户名 + 评论内容 + 【评论时间】
        return AjaxResult.success(lists);
    }
}
